package com.zyh.dom4j.demo1;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

/**
 * @Author zyh
 * @Date 2024/8/13 11:09
 * @Description dom4j 读取xml
 */

public class Dmo4jDemo1 {
    public static void main(String[] args) throws FileNotFoundException, DocumentException {
        //创建一个SAXReader
        SAXReader saxReader = new SAXReader();
        //通过read方法读取文件，拿到文档对象
        Document document = saxReader.read(new FileReader("D:\\Code\\IDEA\\idea_projects\\JavaSE-plus\\day15-code\\src\\com\\zyh\\dom4j\\demo1\\games.xml"));
        //通过文档对象调用getRootElement方法拿到根节点元素
        Element rootElement = document.getRootElement();
        System.out.println("根节点名：" + rootElement.getName());
        List<Element> elements = rootElement.elements();
        for (Element element : elements) {
            System.out.print("\t子节点名：" + element.getName());
            System.out.println("子节点属性：" + element.attributeValue("id"));
            List<Element> sunElements = element.elements();
            for (Element sunElement : sunElements) {
                System.out.print("\t\t孙子节点名：" + sunElement.getName());
                System.out.println("内容为：" + sunElement.getText());
            }
        }
        /*Iterator<Element> elementIterator = rootElement.elementIterator();
        while (elementIterator.hasNext()) {
            Element next = elementIterator.next();
            System.out.println("子标签名："+next.getName()+"子标签id属性"+next.attributeValue("id"));
            Element name = next.element("name");
            Element company = next.element("company");
            System.out.println("孙子标签名："+name.getName()+"孙子标签属性"+name.getText());
            System.out.println("孙子标签名："+company.getName()+"孙子标签属性"+company.getText());
        }*/
    }
}
